import '../../scss/battle.scss'
import React from 'react'
import { commonApi } from '../../api/common'


export default React.createClass({
    getInitialState() {
        return { msgs: [], nextButton: false }
    },
    componentDidMount() {
        this.battle()
    },
    action(data) {
        let self = this
        let fightAttri1 = data.p1.fightAttri
        fightAttri1.name = data.p1.name
        let fightAttri2 = data.p2.fightAttri
        fightAttri2.name = data.p2.name
        let attacker = fightAttri1
        let defender = fightAttri2
        this.state.nextButton = true
        this.setState({ nextButton: this.state.nextButton, msgs: [] })
        let timer = function () {
            setTimeout(function () {
                self.calcAttack(attacker, defender)
                if (attacker.hp > 0 && defender.hp > 0) {
                    let temp = defender
                    defender = attacker
                    attacker = temp
                    timer()
                } else {
                    self.state.nextButton = true
                    self.setState({ nextButton: self.state.nextButton })
                }
            }, 400)
        }
        timer()
    },
    calcAttack(attacker, defender) {
        let defend = defender.defend
        if (defend < 0) {
            defend = 0
        }
        let damage = attacker.attack * attacker.attack / (defend + attacker.attack) //计算伤害
        if (damage <= 0) {
            damage = 1
        }
        damage = Math.ceil(damage)
        defender.hp = defender.hp - damage
        let msg = `${attacker.name}发动了攻击,${defender.name}受到了${damage}点伤害`
        console.log(msg)
        this.sendMsg(msg)
        return damage
    },
    sendMsg(msg) {
        this.state.msgs.push(msg)
        this.setState({ msgs: this.state.msgs })
    },
    battle() {
        let opts = this.props.opts
        let self = this
        let dungeonId = opts.dungeonId
        commonApi.battle({ dungeonId: dungeonId }, function (err, data) {
            self.action(data)
        })
    },
    render() {
        let nextButtonNode
        let msgNode = this.state.msgs.map(function (item) {
            return <p>{item}</p>
        })
        if (this.state.nextButton) {
            nextButtonNode = <button onClick={this.battle}>下一层</button>
        }
        return <div id="battle">
            <div className='msg'>{msgNode}</div>
            {nextButtonNode}

        </div>
    }
})
